/****************************************************
 	文件：ReactiveProperty.cs
 	作者：HuskyT
 	邮箱：1005240602@qq.com
 	日期：2020/3/26 15:41:28
 	功能：响应式属性
 *****************************************************/

using System;

namespace HTFW.Utility.Global
{
    public class ReactiveProperty<T>
    {
        T mValue;

        public T Value
        {
            get => mValue;
            set
            {
                if (mValue.Equals(value) == false)
                {
                    T oldValue = mValue;
                    mValue = value;
                    mOnValueChanged?.Invoke(oldValue, mValue);
                }
            }
        }

        Action<T, T> mOnValueChanged;


        public ReactiveProperty(T initialValue)
        {
            mValue = initialValue;
        }

        public void Subscribe(Action<T, T> onValueChanged)
        {
            mOnValueChanged += onValueChanged;
            mOnValueChanged?.Invoke(mValue, mValue);
        }

        public void UnSubscribe(Action<T, T> onValueChanged)
        {
            if (mOnValueChanged != null)
                mOnValueChanged -= onValueChanged;
        }

        public void UnSubscribeAll()
        {
            mOnValueChanged = null;
        }
    }
}